<template>
  <div class="mt-8">
    <!-- 评论区标题 -->
    <div class="flex items-center justify-between mb-6">
      <div class="pinglun">
        交流区 
      </div>
      <span v-if="commentCount > 0" class="text-gray-500 text-black-10px ml-2"> 
         已留下
         <span class="textstyle">{{ commentCount }}</span>
         条痕迹
        </span>
    </div>
    <!-- 评论禁用 -->
    <div v-if="commentSectionDisabled" class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6 dark:bg-yellow-900 dark:border-yellow-700">
      <div class="flex items-center">
        <svg class="w-5 h-5 text-yellow-500 mr-2 dark:text-yellow-300" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
        </svg>
      </div>
    </div>

    <!-- 评论输入区域 -->
    <div v-else class="bg-white border border-gray-200 rounded-lg p-4 mb-6 dark:bg-gray-800 dark:border-gray-700">
      <div class="mb-4">
        <textarea
          v-model="commentForm.content"
          placeholder="请输入评论内容..."
          class="w-full px-3 py-2 text-gray-700 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
          rows="4"
        ></textarea>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
        <div>
          <input
            v-model="commentForm.nickname"
            type="text"
            placeholder="昵称（必填）"
            :disabled="isUserLoggedIn"
            class="w-full px-3 py-2 text-gray-700 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
            :class="{ 'bg-gray-100 dark:bg-gray-700 cursor-not-allowed': isUserLoggedIn }"
          />
        </div>
      </div>
      <div class="flex justify-end">
        <button
          @click="submitComment"
          :disabled="submitting"
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 dark:bg-blue-500 dark:hover:bg-blue-600"
        >
          {{ submitting ? '提交中...' : '发表评论' }}
        </button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="commentCount > 0">
      <div
        v-for="comment in rootComments"
        :key="comment.id"
        class="rounded-lg p-4 mb-4  "
      >
        <!-- 主评论 -->
        <CommentItem 
          :comment="comment" 
          :reply-form="replyForm"
          :submitting="submitting"
          @reply-to-comment="replyToComment"
          @submit-reply="submitReply"
          @cancel-reply="cancelReply"
        />

        <!-- 回复列表 -->
        <div v-if="getReplies(comment.id).length > 0" class="ml-8 mt-4 space-y-4">
          <div
            v-for="reply in getReplies(comment.id)"
            :key="reply.id"
            class="  border-gray-200 rounded-lg p-3 "
          >
            <CommentItem 
              :comment="reply" 
              :reply-form="replyForm"
              :submitting="submitting"
              @reply-to-comment="replyToComment"
              @submit-reply="submitReply"
              @cancel-reply="cancelReply"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 无评论提示 -->
    <div v-else class="text-center py-8">
      <p class="text-gray-500 dark:text-gray-400">暂无评论，快来抢占沙发吧！</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addComment, getComments, getCommentCount } from '@/api/frontend/comment.js'
import CommentItem from './CommentItem.vue'
import { useStore } from 'vuex'

const props = defineProps({
  articleId: {
    type: [Number, String],
    required: true
  }
})

// 获取store实例
const store = useStore()

// 检查用户是否已登录
const isUserLoggedIn = computed(() => {
  const user = store.state.user
  return user && Object.keys(user).length > 0
})

// 获取登录用户昵称（从setting中获取）
const loggedInUserNickname = computed(() => {
  // 首先尝试从setting中获取昵称
  const setting = store.state.setting
  if (setting && setting.author) {
    console.log('获取昵称：',store.state.setting)
    return setting.author
  }
  
  // 如果setting中没有昵称，尝试从user中获取
  const user = store.state.user
  if (user && Object.keys(user).length > 0) {
    return user.nickname || user.username || ''
  }
  
  return ''
})

// 评论表单
const commentForm = reactive({
  articleId: props.articleId,
  content: '',
  nickname: ''
})

// 回复表单
const replyForm = reactive({
  articleId: props.articleId,
  parentId: null,
  content: '',
  nickname: ''
})

// 评论数据
const comments = ref([])
const commentCount = ref(0)
const submitting = ref(false)
const commentSectionDisabled = ref(false) // 评论区是否禁用

// 计算根评论（没有parentId的评论）
const rootComments = computed(() => {
  return comments.value.filter(comment => !comment.parentId)
})

// 获取回复评论
const getReplies = (parentId) => {
  return comments.value.filter(comment => comment.parentId === parentId)
}

// 提交评论
const submitComment = async () => {
  if (!commentForm.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  // 如果用户未登录，检查昵称
  if (!isUserLoggedIn.value && !commentForm.nickname.trim()) {
    ElMessage.warning('请输入昵称')
    return
  }

  try {
    submitting.value = true
    const res = await addComment(commentForm)
    ElMessage.success(res.message || '评论发表成功，等待审核通过后显示')
    // 清空表单
    commentForm.content = ''
    // 如果用户未登录，清空昵称；如果已登录，保持昵称
    if (!isUserLoggedIn.value) {
      commentForm.nickname = ''
    }
    // 重新加载评论
    await loadComments()
    await loadCommentCount()
  } catch (err) {
    ElMessage.error(err.message || '评论发表失败')
  } finally {
    submitting.value = false
  }
}

// 回复评论
const replyToComment = (comment) => {
  replyForm.parentId = comment.id
  replyForm.content = ''
  // 如果用户已登录，使用登录用户昵称；否则清空昵称
  replyForm.nickname = isUserLoggedIn.value ? loggedInUserNickname.value : ''
}

// 取消回复
const cancelReply = () => {
  replyForm.parentId = null
  replyForm.content = ''
  // 如果用户已登录，使用登录用户昵称；否则清空昵称
  replyForm.nickname = isUserLoggedIn.value ? loggedInUserNickname.value : ''
}

// 提交回复
const submitReply = async () => {
  if (!replyForm.content.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  // 如果用户未登录，检查昵称
  if (!isUserLoggedIn.value && !replyForm.nickname.trim()) {
    ElMessage.warning('请输入昵称')
    return
  }

  try {
    submitting.value = true
    const res = await addComment(replyForm)
    ElMessage.success(res.message || '回复发表成功，等待审核通过后显示')
    // 清空回复表单
    cancelReply()
    // 重新加载评论
    await loadComments()
    await loadCommentCount()
  } catch (err) {
    ElMessage.error(err.message || '回复发表失败')
  } finally {
    submitting.value = false
  }
}

// 加载评论列表
const loadComments = async () => {
  try {
    const res = await getComments({ articleId: props.articleId })
    comments.value = res.data
  } catch (err) {
    console.error('获取评论列表失败:', err)
  }
}

// 加载评论数
const loadCommentCount = async () => {
  try {
    const res = await getCommentCount({ articleId: props.articleId })
    commentCount.value = res.data
  } catch (err) {
    console.error('获取评论数失败:', err)
  }
}

// 格式化时间
const formatDate = (dateString) => {
  // 如果是字符串，先转换为Date对象
  const date = new Date(dateString);
  // 格式化为本地时间字符串
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
}

// 监听用户登录状态变化
watch(isUserLoggedIn, (newVal) => {
  if (newVal) {
    // 用户登录后，自动填充昵称
    commentForm.nickname = loggedInUserNickname.value
  } else {
    // 用户登出后，清空昵称
    commentForm.nickname = ''
  }
})

// 初始化加载
onMounted(async () => {
  await loadComments()
  await loadCommentCount()
  // 检查评论区是否启用
  // 默认不禁用评论区，因为没有专门的API检查文章评论状态
  commentSectionDisabled.value = false
  
  // 如果用户已登录，自动填充昵称
  if (isUserLoggedIn.value) {
    commentForm.nickname = loggedInUserNickname.value
  }
})

// 暴露方法给父组件
defineExpose({
  loadComments,
  loadCommentCount
})
</script>

<style scoped>
.textstyle{
  color: aqua;
  font-size: 52px !important;
}
.pinglun{
  text-align: center !important;
  font-size: 30px !important;
}
</style>